package com.phpxiu.app.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.phpxiu.app.kkylive.R;

/**
 * Created by 吴金洲 on 2016/7/5
 */
public class TopMsgView extends TextView {
    private final static long DELAY=3000;//三秒后隐藏
    private Animation showAnim,hideAnim;
    public TopMsgView(Context context) {
        super(context);
        init(context);
    }

    public TopMsgView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TopMsgView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(21)
    public TopMsgView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context){
        showAnim=AnimationUtils.loadAnimation(context, R.anim.slide_in_from_top);
        showAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                if(getVisibility()!=VISIBLE){
                    setVisibility(VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        hideAnim=AnimationUtils.loadAnimation(context, R.anim.slide_out_to_top);
        hideAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(getVisibility()==VISIBLE){
                    setVisibility(INVISIBLE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 显示
     * @param msg
     */
    public void show(String msg){
        removeCallbacks(hide);
        clearAnimation();
        startAnimation(showAnim);
        setText(msg);
        postDelayed(hide,DELAY);
    }

    /**
     * 隐藏
     */
    public void hide(){
        setText("");
        clearAnimation();
        startAnimation(hideAnim);
    }

    private Runnable hide=new Runnable() {
        @Override
        public void run() {
             hide();
        }
    };
}
